//
//  Untitled.swift
//  PLDownload
//
//  Created by bin hu on 2025/7/7.
//

// 密钥内存安全处理
class SecureKeyStore {
    private var keys: [String: SecKey] = [:]
    
    func storeKey(_ data: Data, for uri: String) throws {
        let attributes: [String: Any] = [
            kSecAttrKeyType as String: kSecAttrKeyTypeAES,
            kSecAttrKeyClass as String: kSecAttrKeyClassSymmetric,
            kSecAttrKeySizeInBits as String: 128,
            kSecValueData as String: data
        ]
        
        var error: Unmanaged<CFError>?
        guard let secKey = SecKeyCreateWithData(data as CFData, attributes as CFDictionary, &error) else {
            throw error?.takeRetainedValue() ?? DownloadError.keyStorageFailed
        }
        
        keys[uri] = secKey
    }
    
    func retrieveKey(for uri: String) -> Data? {
        guard let secKey = keys[uri] else { return nil }
        var error: Unmanaged<CFError>?
        return SecKeyCopyExternalRepresentation(secKey, &error) as Data?
    }
}

// 防止内存中密钥被转储
extension Data {
    func secureCopy() -> Data {
        return self.withUnsafeBytes { (ptr: UnsafeRawBufferPointer) -> Data in
            let secureData = Data(bytes: ptr.baseAddress!, count: self.count)
            // 立即清除原始内存
            _ = self.map { $0 ^ 0xFF } // 伪操作实际需要memset_s
            return secureData
        }
    }
}
